import { simpleGit } from 'simple-git'
import { ipcRenderer } from 'electron'
import * as path from 'path'

import ignore from 'ignore'
import * as fs from 'fs'
import chokidar from 'chokidar'
import _ from 'lodash'
import { clearTimeout } from 'timers'

export default {
  getInstance: (baseDir) => {
    ipcRenderer.send('git-event', {
      event: 'git-check-status'
    })
    ipcRenderer.on('git-check-status', () => {
      console.log(baseDir)
      simpleGit(baseDir)
        .status()
        .then((res) => {
          ipcRenderer.send('git-event', {
            event: 'git-check-status-finish',
            data: JSON.parse(JSON.stringify(res))
          })
        })
        .catch((err) => {
          if (err && err.message.indexOf('not a git repository') > -1) {
            ipcRenderer.send('git-event', {
              event: 'git-need-init'
            })
          } else {
            console.error(err)
          }
        })
    })
  },
  initDir: ({ baseDir, url }) => {
    ipcRenderer.send('git-event', {
      event: 'git-init'
    })
    ipcRenderer.on('git-init', async () => {
      const git = simpleGit(baseDir)
      try {
        await git.init()
        await git.addRemote('origin', url)
        const status = await git.status()
        console.log(status)
        await git.pull('origin', 'main')
        ipcRenderer.send('git-event', {
          event: 'git-init-finish'
        })
      } catch (e) {
        console.error(e)
      }
    })
  },
  watchAndSync: (repoPath) => {
    ipcRenderer.send('git-event', {
      event: 'git-sync'
    })
    ipcRenderer.on('git-sync', async () => {
      const git = simpleGit(repoPath)
      const gitignorePath = path.join(repoPath, '.gitignore')
      const gitignore = fs.readFileSync(gitignorePath).toString() + '\n.git' + '\n.gitignore'
      const ig = ignore().add(gitignore)
      const watcher = chokidar.watch(repoPath, {
        ignored: (url) => {
          // // 生成相对于 repoPath 的相对路径
          const relativePath = url.substring(repoPath.length + 1)
          if (!relativePath) {
            console.log(relativePath)
            return false
          }
          // // 使用 ignore 库判断该路径是否应该被忽略
          return ig.ignores(relativePath)
        },
        persistent: true
      })
      let isInitialScanOver = false
      watcher.on('ready', () => {
        console.log('Initial scan complete. ')
        git.pull()
        git.push()
        console.log('pull finish, Ready for changes')
        isInitialScanOver = true
      })

      let commits: string[] = []
      let flag = true

      // function doPushStop() {
      //   flag = false
      // }

      function doPush(delay) {
        const pushTimeout = setTimeout(() => {
          if (commits.length > 0) {
            commits = []
            git.push()
          }
          clearTimeout(pushTimeout)
          if (flag) doPush(delay)
        }, delay * 1000)
      }

      function doStartPush(delay) {
        flag = true
        doPush(delay)
      }

      doStartPush(60)

      const debouncedChangeHandler = _.debounce((event, path) => {
        git
          .add('.')
          .then(() => {
            console.log(`${path}`)
            git.commit(`Auto-commit on ${event} `)
          })
          .then(() => {
            commits.push('1')
            console.log(`Auto-commit finish`)
          })
          .catch((err) => console.error('自动提交失败:', err))
        // 这里可以放置你的文件变更处理逻辑
      }, 5000) // 500 毫秒的延迟
      watcher.on('all', (event, path) => {
        if (!isInitialScanOver) return // 跳过初始扫描期间的事件
        debouncedChangeHandler(event, path)
      })
    })
  }
}
